/**
 * 
 */
package com.jxc.service.impl;


import java.awt.BasicStroke;
import java.awt.Color;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Hibernate;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.AuditRecord;
import com.jxc.model.po.Goods;
import com.jxc.model.po.Member;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.SaleDayTotal;
import com.jxc.model.po.SaleReturnlist;
import com.jxc.model.po.SaleReturnlistItem;
import com.jxc.model.po.Salelist;
import com.jxc.model.po.SalelistItem;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VSalelistItem;
import com.jxc.model.vo.VUser;
import com.jxc.service.MemberServiceI;
import com.jxc.service.SalelistServiceI;
import com.jxc.service.UserServiceI;


/**
 * @author Tino
 * 
 */
@Service("salelistService")
public class SalelistServiceImpl implements SalelistServiceI {

	@Autowired
	private BaseDaoI<Salelist> salelistDao;
	@Autowired
	private BaseDaoI<SalelistItem> itemDao;
	@Autowired
	private BaseDaoI<AuditRecord> auditRecordDao;
	@Autowired
	private MemberServiceI memberService;
	@Autowired
	private UserServiceI userService;
	@Override
	public DataGrid datagridNoPage(VSalelist vSalelist) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.findNoPage(vSalelist)));
		return dg;
	}

	private List<Salelist> findNoPage(VSalelist vSalelist) {
		String hql = "from Salelist t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vSalelist, hql, values);

		return salelistDao.find(hql, values);
	}

	@Override
	public List<VSalelistItem> getItems(VSalelist vSalelist) {
		String hql = "from SalelistItem t where t.refund=false";
		
		List<Object> values = new ArrayList<Object>();
		if(vSalelist.getId()!=null){
			hql +=" and t.salelist.id = ? ";
			values.add(vSalelist.getId());
		}
		if(vSalelist.getSerial()!=null){
			hql +=" and t.salelist.serial = ? ";
			values.add(vSalelist.getSerial());
		}
		List<SalelistItem> list = itemDao.find(hql, values);
		return changeModelByItem(list);
	}
	private List<VSalelistItem> changeModelByItem(List<SalelistItem> items){
		List<VSalelistItem> vItems = new ArrayList<VSalelistItem>();
		try {
			if(items!=null&&items.size()>0){
				for(SalelistItem item:items){
					VSalelistItem vItem = new VSalelistItem();
					BeanUtils.copyProperties(item, vItem);
					Goods goods = item.getGoods();
					if(goods!=null){
						vItem.setGid(goods.getId());
						vItem.setGname(goods.getName());
						vItem.setGcolor(goods.getColor());
						vItem.setGsize(goods.getSize());
						vItem.setGbarcode(goods.getBarcode());
						vItem.setGtype(goods.getType());
					}
					SaleReturnlist sr = new SaleReturnlist();
					if(item.getSalelist()!=null){
						vItem.setWipeZero(item.getSalelist().getWipeZero());
						if(item.getSalelist().getSalereturnlists()!=null&&item.getSalelist().getSalereturnlists().size()!=0){
							sr = item.getSalelist().getSalereturnlists().get(0);
						}
					}
					if(sr!=null){
						vItem.setSrid(sr.getId());
						if(sr.getItems()!=null){
							for (SaleReturnlistItem si: sr.getItems()) {
								if(goods!=null&&si.getGoods()!=null){
									if(goods.getId()==si.getGoods().getId()){
										vItem.setReturnnum(si.getNum());
										vItem.setReturnmoney(si.getTotal());
										vItem.setSritemid(si.getId());
									}
								}
							}
						}
						
					}
					vItems.add(vItem);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vItems;
	}

	@Override
	public VSalelist getSalelistById(Long id) {
		Salelist salelist = salelistDao.get(Salelist.class, id);
		if(salelist!=null){
			VSalelist vSalelist = new VSalelist();
			BeanUtils.copyProperties(salelist, vSalelist);
			User user = salelist.getUser();
			if (user != null) {
				vSalelist.setUid(user.getId());
				vSalelist.setUusername(user.getUsername());
			}
			Member member = salelist.getMember();
			if (member != null) {
				vSalelist.setMid(member.getId());
				vSalelist.setMname(member.getName());
			}
			Repertory repertory = salelist.getRepertory();
			if (repertory != null) {
				vSalelist.setRid(repertory.getId());
				vSalelist.setRname(repertory.getName());
			}
			return vSalelist;
		}else{
			return null;
		}
	}

	@Override
	public List<VSalelistItem> getItemsByIds(String ids) {
		List<SalelistItem> items = new ArrayList<SalelistItem>();
		String[] strIds = ids.split(",");
		for(String strId:strIds){
			SalelistItem item = itemDao.get(SalelistItem.class, Long.parseLong(strId));
			if(item!=null){
				items.add(item);
			}
		}
		return changeModelByItem(items);
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#combobox(com.jxc.model.vo.VSalelist)
	 */
	@Override
	public List<VSalelist> combobox(VSalelist vsl) {
		return this.changeModel(this.find(vsl));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#datagrid(com.jxc.model.vo.VSalelist)
	 */
	@Override
	public DataGrid datagrid(VSalelist vsl) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vsl)));
		dg.setTotal(this.total(vsl));
		return dg;
	}
	
	public void edit(){
		
	}
	
	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#datagridTotal(com.jxc.model.vo.VSalelist)
	 */
	public DataGrid datagridTotal(VSalelist vsl) {
		DataGrid dg = new DataGrid();	
		List<Object[]> vsls = saleTotal(vsl);
		dg.setRows(this.changeModelTotal(vsls,vsl));
		dg.setTotal((long) vsls.size());
		return dg;
	}
	
	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#datagridTotal(com.jxc.model.vo.VSalelist)
	 */
	public DataGrid datagridRank(VSalelist vsl) {
		DataGrid dg = new DataGrid();	
		List<Object[]> vsls = saleRank(vsl);
		dg.setRows(this.changeModelRank(vsls,vsl));
		dg.setTotal((long) vsls.size());
		return dg;
	}
	
	public DataGrid datagridsettlementTotal(VSalelist vsl) {
		DataGrid dg = new DataGrid();		
		dg.setRows(this.changeModelsettlementTotal(this.findsettlementTotal(vsl)));
		//dg.setTotal(this.totalsettlementTotal(vsl));
		return dg;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#delete(java.lang.String)
	 */
	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					Salelist ct = salelistDao.get(Salelist.class, Long.parseLong(id.trim()));
					if (ct != null) {
						salelistDao.delete(ct);
					}
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#save(com.jxc.model.vo.VSalelist)
	 */
	@Override
	public Long save(VSalelist vsl) {
		Salelist st = new Salelist();
		BeanUtils.copyProperties(vsl, st);
		if (vsl.getUid() != null) {
			st.setUser(new User(vsl.getUid()));
		}
		if (vsl.getMid() != null) {
			st.setMember(new Member(vsl.getMid()));
		}
		if (vsl.getRid() != null) {
			st.setRepertory(new Repertory(vsl.getRid()));
		}
		this.salelistDao.save(st);
		return st.getId();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#search(com.jxc.model.vo.VSalelist)
	 */
	@Override
	public List<VSalelist> search(VSalelist vsl) {
		List<Salelist> sls = this.find(vsl);
		for (Salelist sl : sls) {
			Hibernate.initialize(sl.getItems());
		}
		return this.changeModel(sls);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistServiceI#update(com.jxc.model.vo.VSalelist)
	 */
	@Override
	public void update(VSalelist vsl) {
		Salelist st = this.salelistDao.get(Salelist.class, vsl.getId());
		BeanUtils.copyProperties(st, vsl, new String[] { "id" });
		if (vsl.getUid() != null) {
			st.setUser(new User(vsl.getUid()));
		}
		if (vsl.getMid() != null) {
			st.setMember(new Member(vsl.getMid()));
		}
		if (vsl.getRid() != null) {
			st.setRepertory(new Repertory(vsl.getRid()));
		}
		this.salelistDao.update(st);
	}

	private List<VSalelist> changeModel(List<Salelist> sls) {
		List<VSalelist> vsls = new ArrayList<VSalelist>();
		if (sls != null && sls.size() > 0) {
			for (Salelist sl : sls) {
				VSalelist vsl = new VSalelist();
				BeanUtils.copyProperties(sl, vsl);
				if (sl.getUser() != null) {
					User user = sl.getUser();
					vsl.setUid(user.getId());
					vsl.setUusername(user.getUsername());
				}

				boolean retrunGoods=isReturnGoods(sl.getId().toString());
				
				if(retrunGoods){
					vsl.setReturnGoods("有退货");
				}
				
				if (sl.getMember() != null) {
					Member member = sl.getMember();
					vsl.setMid(member.getId());
					vsl.setMname(member.getName());
					vsl.setNowpoint(member.getPoint());
				/*	if (sl.getUser() != null) {
						User user = sl.getUser();
						if(user.getUser()!=null){
							if(user.getUser().getUserType()!=0){
								//如果是经销商会员型,按照会员折扣
								if(user.getUser().getUserType()==1){
									if(sl.getMember().getMemberType()!=null){
										if(sl.getMember().getMemberType().getDiscount()!=null){
											vsl.setDiscountNum(sl.getMember().getMemberType().getDiscount().getDiscountNum());
										}
									}	
								}//如果是经销商品牌型,按照品牌折扣
								if(user.getUser().getUserType()==5){
									if()
								}
							}
						}
						vsl.setUid(user.getId());
						vsl.setUusername(user.getUsername());
					}*/
					
				}

				if (sl.getRepertory() != null) {
					Repertory repertory = sl.getRepertory();
					vsl.setRid(repertory.getId());
					vsl.setRname(repertory.getName());
				}if (sl.getUser() != null) {
					User user = sl.getUser();
					vsl.setUid(user.getId());
					vsl.setUusername(user.getRealName());					
				}

				vsls.add(vsl);
			}
		}
		return vsls;
	}

	
	//查询商品是否有退货 传入商品的id
	private boolean isReturnGoods(String id){
		String hql="select count(*) from xsgl_salelist s,xsgl_salereturnlist t where s.id=t.salelist_id and s.id='"+id+"'";
		BigInteger l = salelistDao.countSQL(hql); 
		return l.intValue()>0;
	}
	
	/**
	 * 把List<object[]>类型的销售统计数据封装成对象用于datagrid显示
	 * @param sls
	 * @param model
	 * @return
	 */
	private List<VSalelist> changeModelTotal(List<Object[]> sls,VSalelist model) {
		// TODO Auto-generated method stub

		List<VSalelist> vsls = new ArrayList<VSalelist>();
		
		if (sls != null && sls.size() > 0) {
			for (int i = 0;i < sls.size();i++) {
				VSalelist vsl = new VSalelist();
				if(model.getGroupby()!=null&&model.getGroupby().trim().equals("user")){
					vsl.setUusername((String)(sls.get(i)[0]));
				}else if(model.getGroupby()!=null&&model.getGroupby().trim().equals("repertory")){
					vsl.setRname((String)(sls.get(i)[0]));
				}else if(model.getGroupby()!=null&&model.getGroupby().trim().equals("brand")){
					vsl.setBname((String)(sls.get(i)[0]));
				}else{
					vsl.setUusername((String)(sls.get(i)[0]));
				}
				vsl.setTotal(Double.parseDouble(String.valueOf(sls.get(i)[1])));
				vsl.setBuyprice(Double.parseDouble(String.valueOf(sls.get(i)[2])));
				vsl.setProfit(Double.parseDouble(String.valueOf(sls.get(i)[3])));
				vsls.add(vsl);
			}
		}
		return vsls;
	}	
	
	/**
	 * 把List<object[]>类型的商品销售排行数据封装成对象用于datagrid显示
	 * @param sls
	 * @param model
	 * @return
	 */
	private List<VGoods> changeModelRank(List<Object[]> sls,VSalelist model) {
		// TODO Auto-generated method stub

		List<VGoods> vsls = new ArrayList<VGoods>();
		
		if (sls != null && sls.size() > 0) {
			for (int i = 0;i < sls.size();i++) {
				VGoods vg = new VGoods();
				if(model.getGroupby().trim().equals("brand")){//通过品牌统计
					vg.setBname((String)(sls.get(i)[0]));
				}else if(model.getGroupby().trim().equals("color")){//通过颜色统计
					vg.setColor((String)(sls.get(i)[0]));
				}else if(model.getGroupby().trim().equals("size")){//通过尺码统计
					vg.setSize((String)(sls.get(i)[0]));
				}else if(model.getGroupby().trim().equals("type")){//通过款号统计
					vg.setType((String)(sls.get(i)[0]));
				}else if(model.getGroupby().trim().equals("gtype")){//通过商品类型统计
					vg.setGtname((String)(sls.get(i)[0]));
				}else{//通过品牌统计
					vg.setBname((String)(sls.get(i)[0]));
				}
				vg.setTotal(Double.parseDouble(String.valueOf(sls.get(i)[1])));
				vg.setBuyPrice(Double.parseDouble(String.valueOf(sls.get(i)[2])));
				vg.setProfit(Double.parseDouble(String.valueOf(sls.get(i)[3])));
				vsls.add(vg);
			}
		}
		return vsls;
	}	
	

	private List<VSalelist> changeModelsettlementTotal(List<AuditRecord> sls) {
		List<VSalelist> vsls = new ArrayList<VSalelist>();
		if (sls != null && sls.size() > 0) {
			for (AuditRecord sl : sls) {
				VSalelist vsl = new VSalelist();
				BeanUtils.copyProperties(sl, vsl);	
				vsl.setBeginDate(sl.getBeginAudit());
				vsl.setEndDate(sl.getEndAudit());
				if (sl.getUser() != null) {
					User user = sl.getUser();
					vsl.setUid(user.getId());
					vsl.setUusername(user.getRealName());
				}
				if (sl.getRepertory() != null) {
					Repertory repertory = sl.getRepertory();
					vsl.setRid(repertory.getId());
					vsl.setRname(repertory.getName());
				}		
				if (sl.getUser() != null) {
					User user = sl.getUser();
					vsl.setUid(user.getId());
					vsl.setUusername(user.getUsername());
				}
				vsls.add(vsl);		
			}
		}
		return vsls;
	}	
	
	public Date strToDate(String strDate) {   
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd".trim().substring(0, 10));   
        ParsePosition pos = new ParsePosition(0);   
        Date strtodate = formatter.parse(strDate.trim().substring(0,10), pos);  
        return strtodate;   
    }
	
	
	private List<Salelist> find(VSalelist vsl) {
		String hql = "select t from Salelist t join t.items i where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vsl, hql, values);
		hql += "group by t.id";
		if (vsl.getSort() != null && vsl.getOrder() != null) {
			hql += " order by " + vsl.getSort() + " " + vsl.getOrder();
		}
		return salelistDao.find(hql, values, vsl.getPage(), vsl.getRows());
	}
	
	private List<Salelist> findTotal(VSalelist vsl) {
		String hql = "select t from Salelist t  where 1=1  ";
		
		List<Object> values = new ArrayList<Object>();
		hql = addWhereTotal(vsl, hql, values);
		
		hql += " GROUP BY t.user,t.repertory order by sum(t.total) DESC "; 
		return salelistDao.find(hql, values, vsl.getPage(), vsl.getRows());	
	}
	
    private Double findTotalSum(Salelist sls,VSalelist vsls) {			
		String hql = "select sum(t.total) from Salelist t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		if (sls.getRepertory() != null && sls.getUser() != null) {
			hql += " and t.repertory.id = ? and t.user.id = ? ";
			values.add(sls.getRepertory().getId());
			values.add(sls.getUser().getId());
		}
		if(vsls.getBeginDate() != null && vsls.getEndDate() != null){
			hql += " and t.date >= ? and t.date <= ? ";
			values.add(vsls.getBeginDate());
			values.add(vsls.getEndDate());
		}
		hql += " GROUP BY t.user,t.repertory order by sum(t.total) DESC  ";
		return salelistDao.countToDouble(hql, values);
	}
    
    private List<AuditRecord> findsettlementTotal(VSalelist vsl) {
		String hql = " from AuditRecord t where 1=1  ";
		
		List<Object> values = new ArrayList<Object>();
		hql = addWheresettlementTotal(vsl, hql, values);
		
		hql += " order by t.id DESC  ";
		
		return auditRecordDao.find(hql, values, vsl.getPage(), vsl.getRows());	
	}

	private Long total(VSalelist vsl) {
		String hql = "select count(*) from (select count(*) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r " +
				" where t.id=i.salelist_id  and  i.goods_id=g.id and t.repertory_id=r.id ";
		if (vsl.getId() != null) {
			hql += " and t.id = "+vsl.getId();
		}
		if(vsl.getSerial()!=null&&!vsl.getmSerial().trim().equals("")){
			hql += "and t.serial like '%"+vsl.getSerial()+"%'";
		}
		if (vsl.getUid() != null) {
			hql += " and t.user_id = "+vsl.getUid();
		}
		if (vsl.getUpid() != null) {
			hql += " and r.user_id = "+vsl.getUpid();
		}
		if (vsl.getMid() != null) {
			hql += " and t.member_id = "+vsl.getMid();
		}

		if (vsl.getRid() != null) {
			hql += " and t.repertory_id ="+vsl.getRid();
		}

		if (vsl.getBeginDate() != null) {
			hql += " and t.date >= '"+vsl.getBeginDate().toLocaleString()+"'";
		}

		if (vsl.getEndDate() != null) {
			hql += " and t.date <= '"+vsl.getEndDate().toLocaleString()+"'";
		}
		if (vsl.getGtype() != null&&!vsl.getGtype().trim().equals("")) {
			hql += " and g.type like '%"+vsl.getGtype()+"%'";
		}
		hql += " group by t.id)aa";
		BigInteger l = salelistDao.countSQL(hql); 
		return l.longValue();
	}

	private Long totalTotal(VSalelist vsl) {
		String hql = "select count(*) from Salelist t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhereTotal(vsl, hql, values);
		
		hql += " GROUP BY t.user,t.repertory order by sum(t.total) DESC "; 
		
		return salelistDao.count(hql, values);
	}
	
	private Long totalsettlementTotal(VSalelist vsl) {
		String hql = "select count(*) from AuditRecord t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWheresettlementTotal(vsl, hql, values);
		return salelistDao.count(hql, values);
	}
	private String addWhere(VSalelist vsl, String hql, List<Object> values) {
		if (vsl.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vsl.getId());
		}
		if(vsl.getSerial()!=null){
			hql += "and t.serial like ?";
			values.add(vsl.getSerial()+"%%");		
		}
		
		if (vsl.getUpid() != null) {
			hql += " and t.repertory.user.id = ? ";
			values.add(vsl.getUpid());
		}
		
		if(vsl.getUid() != null) {
			hql += " and t.user.id = '"+vsl.getUid()+"'";
			//values.add(vsl.getUid());
		}
		
		if (vsl.getMid() != null) {
			hql += " and t.member.id = ? ";
			values.add(vsl.getMid());
		}
		if(vsl.getmSerial()!=null&&!vsl.getmSerial().trim().equals("")){
			hql += " and t.member.name = ? ";
			values.add(vsl.getmSerial());
		}

		if (vsl.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vsl.getRid());
		}

		if (vsl.getBeginDate() != null) {
			hql += " and t.date >= ? ";
			values.add(vsl.getBeginDate());
		}

		if (vsl.getEndDate() != null) {
			hql += " and t.date <= ? ";
			values.add(vsl.getEndDate());
		}
		if (vsl.getGtype() != null&&!vsl.getGtype().trim().equals("")) {
			hql += " and i.goods.type like ? ";
			values.add(vsl.getGtype()+"%");
		}
		return hql;
	}
	
	private String addWhereTotal(VSalelist vsl, String hql, List<Object> values) {
		
		/*if (vsl.getUusername() != null) {
			hql += " and t.user.id = ? ";
			values.add(vsl.getUid());
		}*/
		
		if (vsl.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vsl.getRid());
		}

		if (vsl.getBeginDate() != null) {
			hql += " and t.date >= ? ";
			values.add(vsl.getBeginDate());
		}

		if (vsl.getEndDate() != null) {
			hql += " and t.date <= ? ";
			values.add(vsl.getEndDate());
		}
		return hql;
	}
	
    private String addWheresettlementTotal(VSalelist vsl, String hql, List<Object> values) {		
		if (vsl.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vsl.getRid());
		}
		
		if(vsl.getUpid()!=null){
			hql += " and t.user.user.id = ? ";
			values.add(vsl.getUpid());
		}
		if (vsl.getBeginDate() != null) {
			hql += " and t.beginAudit >= ? ";
			values.add(vsl.getBeginDate());
		}

		if (vsl.getEndDate() != null) {
			hql += " and t.endAudit <= ? ";
			values.add(vsl.getEndDate());
		}
		return hql;
	}

	@Override
	public void editModel(VSalelist model) {
		try {
			  if(model.getMids()!=null&&!model.getMids().trim().equals("")){
					String[] mids = model.getMids().split(",");
					for (int i = 0; i < mids.length; i++) {
						String sid = mids[i];
						String mid = mids[++i];
						VSalelist vs = new VSalelist();
						vs.setId(new Long(sid));
						vs.setMid(new Long(mid));
						Salelist sa = new Salelist(new Long(sid));
						BeanUtils.copyProperties(sa, vs);
						this.update(vs);
						
						
						//修改会员积分
						
								VMember vm = new VMember();
								Member m = memberService.getMemberById(new Long(mid));
								BeanUtils.copyProperties(m, vm);
								Integer moneyPointProp = 1;
								if(vm.getUid()!=null&&userService.get(vm.getUid()).getMoneyPointProp()!=null){
									moneyPointProp = userService.get(vm.getUid()).getMoneyPointProp();
								}
								if(vm.getPoint()==null){
									vm.setPoint(0);
								}
								if(vs.getRealPay()!=null){
									if(vs.getCharge()!=null){//找零非空的情况
										vm.setPoint(new Integer(((int)(vm.getPoint()+(vs.getRealPay()-vs.getCharge())/moneyPointProp))));
										vm.setConsume(vm.getConsume()+(vs.getRealPay()-vs.getCharge()));
										memberService.update(vm);

									}else{//没有找零
										vm.setPoint(new Integer(((int)(vm.getPoint()+vs.getRealPay()/moneyPointProp))));
										vm.setConsume(vm.getConsume()+vs.getRealPay());
										memberService.update(vm);

									}
								} 
						} 
			  }			
				
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String addWhereGather(VSalelist vsl,String hql){
		if (vsl.getId() != null) {
			hql += " and t.id = "+vsl.getId();
		}
		if(vsl.getSerial()!=null&&!vsl.getmSerial().trim().equals("")){
			hql += "and t.serial like '%"+vsl.getSerial()+"%'";
		}
		if (vsl.getUid() != null) {
			hql += " and t.user_id = "+vsl.getUid();
		}
		if (vsl.getUpid() != null) {
			hql += " and r.user_id = "+vsl.getUpid();
		}
		if (vsl.getMid() != null) {
			hql += " and t.member_id = "+vsl.getMid();
		}

		if (vsl.getRid() != null) {
			hql += " and t.repertory_id ="+vsl.getRid();
		}

		if (vsl.getBeginDate() != null) {
			hql += " and t.date >= '"+vsl.getBeginDate().toLocaleString()+"'";
		}

		if (vsl.getEndDate() != null) {
			hql += " and t.date <= '"+vsl.getEndDate().toLocaleString()+"'";
		}
		if (vsl.getGtype() != null&&!vsl.getGtype().trim().equals("")) {
			hql += " and g.type like '%"+vsl.getGtype()+"%'";
		}
		return hql;
	}
	
	@Override
	/*
	 * 前台销售记录查询的汇总(non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#findGather(com.jxc.model.vo.VSalelist)
	 */
	public Object findGather(VSalelist model) { 
		VSalelist vsa = new VSalelist();
		try{
			
			//销售总金额
			/* select count(*) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g" +
			" where t.id=i.salelist_id  and  i.goods_id=g.id */
			//
			
			//错误原因，对每一个商品进行重复统计价格，应该用i.total 统计每一单的金额 
//			String hql = "select sum(t.total) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r " +
//			" where t.id=i.salelist_id  and  i.goods_id=g.id and r.id=t.repertory_id ";
			
			String hql = "select sum(i.total) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r " +
			" where t.id=i.salelist_id  and  i.goods_id=g.id and r.id=t.repertory_id ";
			hql = addWhereGather(model, hql);
		    Double  xs  =  salelistDao.countSQL1(hql);
		    if(xs==null)xs=0d;
		    Double xsje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xs));
		    //抹零金额
			String hql2 = " select sum(t.wipezero) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r " +
			" where t.id=i.salelist_id  and  i.goods_id=g.id  and r.id=t.repertory_id ";
			hql2 = addWhereGather(model, hql2);
			Double mlje = salelistDao.countSQL1(hql2);
			if(mlje==null)mlje=0d;
			Double ml = Double.parseDouble(new java.text.DecimalFormat("#.00").format(mlje));
			if(ml==null)ml=0d; 
			//退货金额
			String hql3 = " select sum(s.total) from xsgl_salereturnlist_item s,xsgl_salereturnlist l," +
					" xsgl_salelist t,spgl_goods g,rkgl_repertory r where g.id=s.GOODS_ID and l.id=s.salereturnlist_id" +
					" and l.salelist_id=t.id  and r.id=l.repertory_id ";
			hql3 = addWhereGather(model, hql3);
			Double thje = salelistDao.countSQL1(hql3);
			if(thje==null)thje=0d;
			Double th = Double.parseDouble(new java.text.DecimalFormat("#.00").format(thje));
			
			if(th==null)th=0d; 
			vsa.setThzje(th);
			//实际销售总金额
			//Double sjje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xsje-ml-th)); //不應該在減去退款金額
			Double sjje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xsje-ml));
			
			vsa.setXszje(sjje);
			
			//销售数量
			String hql4 = "select sum(i.number) from  xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r" +
			" where t.id=i.salelist_id  and  i.goods_id=g.id  and r.id=t.repertory_id ";
			hql4 = addWhereGather(model, hql4);
			BigDecimal bd = salelistDao.countSQL2(hql4);
			if(bd==null)bd=new BigDecimal(0);
			Long xssl = Long.valueOf(String.valueOf(bd));
			if(xssl==null)xssl=0l;
			//退货数量
			String hql5 = "select sum(s.num) from xsgl_salereturnlist_item s,xsgl_salereturnlist l," +
					" xsgl_salelist t,spgl_goods g,rkgl_repertory r where g.id=s.GOODS_ID and l.id=s.salereturnlist_id" +
					" and l.salelist_id=t.id  and r.id=l.repertory_id  ";
			hql5 = addWhereGather(model, hql5);
			BigDecimal bd2 = salelistDao.countSQL2(hql5);
			if(bd2==null)bd2=new BigDecimal(0);
			Long thsl = Long.valueOf(String.valueOf(bd2));
			if(thsl==null)thsl=0l;
		
			vsa.setXsthsl(thsl);
		
			//实际销售总数量 
			//vsa.setSjxszs(xssl-thsl); //直接计算销售记录中的数量即可,因为在退货的时候 已经对数量进行减少了
			vsa.setSjxszs(xssl);
			//优惠金额
			String hql6 = " select sum(t.viptotal) from xsgl_salelist t,xsgl_salelist_item i,spgl_goods g,rkgl_repertory r " +
			" where t.id=i.salelist_id  and  i.goods_id=g.id  and r.id=t.repertory_id ";
			hql6 = addWhereGather(model, hql6);
			Double yhje = salelistDao.countSQL1(hql6);
			if(yhje==null)yhje=0d;
			Double yh = Double.parseDouble(new java.text.DecimalFormat("#.00").format(yhje));
			if(yh==null)yh=0d; 
			//实际优惠金额
			Double shhyje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(yhje+ml));
			
			vsa.setYhzje(shhyje);
			 //吊牌价总金额
//			
//		    String hql8 = "select sum(d.num*t.showPrice) from GoodsRepertory d join d.goods t join t.brand b join d.repertory r where " +
//		    		" t.isDelete=false and b.isDelete=false and  r.isDelete=false ";
//		    hql8 = addWhereGather(model, hql8);
//		    Double dpzje = salelistDao.count1(hql8);
//		    if(dpzje==null)dpzje=0d;
//		    Double dp = Double.parseDouble(new java.text.DecimalFormat("#.00").format(dpzje));
//		    if(dp==null)dp=0d;
//		    vsa.setDpzje(dp);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return vsa;
	}

	@Override
	public List<VSalelistItem> findSaleDetail(VSalelist model) {
		List<SalelistItem> sa = new ArrayList<SalelistItem>();
		try {
			if(model.getId()!=null){
				List<Object> values = new ArrayList<Object>();
				String hql = " select t from SalelistItem t where t.salelist.id = ? ";
				values.add(model.getId());
			    sa = itemDao.find(hql, values, model.getPage(), model.getRows());				}
			
				return changeModelsale(sa);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	private List<VSalelistItem> changeModelsale(List<SalelistItem> slis) {
		List<VSalelistItem> vslis = new ArrayList<VSalelistItem>();
		if (slis != null && slis.size() > 0) {
			for (SalelistItem sli : slis) {
				VSalelistItem vsli = new VSalelistItem();
				BeanUtils.copyProperties(sli, vsli);
				if (sli.getGoods() != null) {
					Goods goods = sli.getGoods();
					vsli.setGid(goods.getId());
					vsli.setGname(goods.getName());
					vsli.setGbarcode(goods.getBarcode());
					vsli.setGtype(goods.getType());
					if(goods.getBrand()!=null){
						vsli.setBname(goods.getBrand().getName());
					}
					vsli.setGcolor(goods.getColor());
					vsli.setGsize(goods.getSize());
				}
				if (sli.getSalelist() != null) {
					Salelist sl = sli.getSalelist();
					vsli.setSlid(sl.getId());
				}
				vslis.add(vsli);
			}
		}
		return vslis;
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#userSaleTotal(java.lang.Long, com.jxc.model.vo.VSalelist)
	 */
	@Override
	public List<Object[]> saleTotal( VSalelist model) {
		// TODO Auto-generated method stub
		List<Object[]> vsls = new ArrayList<Object[]>();
		/*String sql = " FROM (SELECT  u.user_name username,u.real_name realname,r.name repertoryname,sl.total total,SUM(g.buy_price) buyprice ,sl.total-SUM(g.buy_price) profit " +
				"FROM  `xsgl_salelist_item` sli JOIN `xsgl_salelist` sl JOIN `spgl_goods` g  JOIN `rkgl_repertory` r JOIN `qxgl_user` u " +
				"WHERE sli.salelist_id=sl.id AND sli.goods_id=g.id AND sl.repertory_id=r.id AND sl.user_id=u.id AND r.user_id='"+ model.getUpid() +"' GROUP BY sl.id) t " ;*/
		

		
		String sql = " ROUND(SUM(sli.total),2) total,ROUND(SUM(g.buy_price*sli.number),2) buyprice ," +
				"ROUND(SUM(sli.total)-SUM(g.buy_price*sli.number),2) profit FROM  `xsgl_salelist_item` sli " +
				"JOIN `xsgl_salelist` sl JOIN `qxgl_user` u JOIN `rkgl_repertory` r JOIN `spgl_goods` g  JOIN `spgl_brand` b " +
				"JOIN `spgl_goods_type` gt WHERE sli.goods_id=g.id AND sli.salelist_id=sl.id AND sl.user_id=u.id AND sl.repertory_id=r.id " +
				"AND g.brand_id=b.id AND  g.goods_type_id=gt.id AND u.user_id="+model.getUpid();
				
				//仓库
				if(model.getRid()!=null){
					sql+=" and r.id="+model.getRid();
				}
				
				//销售时间
				if(model.getBeginDate()!=null&&model.getEndDate()!=null){
					
					DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
					
					sql+=" and sl.date>='"+format.format(model.getBeginDate())+"' and sl.date<='"+format.format(model.getEndDate())+"'";
					
				}
				
				sql+=" GROUP BY ";
		
		try{
			if(model.getGroupby().trim().equals("user")){//通过营业员统计
				sql = "SELECT CONCAT(u.user_name,'[',u.real_name,']') username, " + sql + " u.user_name ORDER BY total DESC ";
			}else if(model.getGroupby().trim().equals("repertory")){//通过仓库统计
				sql = "SELECT r.name repertoryname, " + sql + " r.name ORDER BY total DESC ";
			}else if(model.getGroupby().trim().equals("brand")){//通过品牌统计
				sql = "SELECT b.name brandname, " + sql + " b.name ORDER BY total DESC ";
			}else{//默认通过营业员统计
				sql = "SELECT CONCAT(u._username,'[',u.real_name,']') username, " + sql + " u.user_name ORDER BY total DESC ";
			}
			vsls = salelistDao.findBySql(sql);
			
		}catch(Exception e){
			e.printStackTrace();
		}		
		
		return vsls;		
		
	}
	
	/**
	 * 创建日销售分析图
	 */
	@Override
	public JFreeChart saleDayTotalJFreeChat(List<VRepertory> repertories,VSalelist model,VUser user){
		
		//如果当前时间为空的话就给一个当前的日期
		if(model.getBeginDate()==null){
			model.setBeginDate(new Date());
		}
			
		 // 定义图表对象
		   JFreeChart chart = ChartFactory.createLineChart((model.getBeginDate().getMonth()+1)+"月份销售曲线", //折线图名称
		     "时间", // 横坐标名称
		     "销售额(元)", // 纵坐标名称
		     getSaleDatTotalDataset(repertories,model,user), // 数据
		     PlotOrientation.VERTICAL, // 水平显示图像
		     true, // include legend
		     true, // tooltips
		     false // urls
		     );
		   CategoryPlot plot = chart.getCategoryPlot();
		   plot.setRangeGridlinesVisible(true); //是否显示格子线
		   plot.setBackgroundAlpha(0.3f); //设置背景透明度
		   NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
		   //标准刻度单位
		   rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		   //设置自动范围包括零
		   rangeAxis.setAutoRangeIncludesZero(true);
		   //边缘距离
		   //rangeAxis.setUpperMargin(0.20);
		   rangeAxis.setUpperMargin(0.50);
		   //角度
		   rangeAxis.setLabelAngle(Math.PI / 2.0);

		   return chart;
		
	}
	
	/**
	 * 为日销售分析准备数据
	 * @return
	 */
	 private DefaultCategoryDataset getSaleDatTotalDataset(List<VRepertory> repertories,VSalelist model,VUser user){
		 
		 //JfreeChat 数据对象
		 DefaultCategoryDataset linedataset = new DefaultCategoryDataset();
		 
		 //日销售数据
		  List<SaleDayTotal> saleDayTotals=changeModelDayTotals(repertories,model,user);
		  
		  for(int i=1;i<=saleDayTotals.size();i++){
			  
			  SaleDayTotal total=saleDayTotals.get(i-1);
			  if(total!=null){
				  String rname=total.getRname();
				  for(int j=0;j<total.getDays().length;j++){
					  
					  //linedataset.addValue(100+i, rname,(j+1)+"");
					  linedataset.addValue(total.getDays()[j], rname,(j+1)+"");  
				  }		
			  }
		  }

		  	
		 
		 return linedataset;
	 }
	
	/**
	 * 日销售分析
	 * @param repertories
	 * @param vsl
	 * @param user
	 * @return
	 */
	@Override
	public DataGrid datagridDayTotal(List<VRepertory> repertories,VSalelist vsl,VUser user){
		DataGrid dg = new DataGrid();	
		dg.setRows(this.changeModelDayTotals(repertories, vsl, user));
		dg.setTotal((long) dg.getRows().size());
		return dg;
	}
	/**
	 * 获取所有仓库每一天的营业额
	 * @param vList
	 * @param vSalelist
	 * @param user
	 * @return
	 */
	private List<SaleDayTotal> changeModelDayTotals(List<VRepertory> repertories,VSalelist model,VUser user){
		
		List<SaleDayTotal> list=new ArrayList<SaleDayTotal>();
		
		if(model.getRid()!=null){
			List<Object[]> vsls = saleDayTotal(model, user);
			list.add(changeDayTotals(vsls));
		}else{
			
			for(VRepertory repertory:repertories){
				model.setRid(repertory.getId());
				List<Object[]> vsls = saleDayTotal(model, user);
				if(changeDayTotals(vsls)!=null){
					list.add(changeDayTotals(vsls));
				}
			}
			
		}
		
		
		return list;
	}
	
	/**
	 * 获取指定仓库 每一天的营业额
	 * @param list
	 * @param model
	 * @return
	 */
	private SaleDayTotal changeDayTotals(List<Object[]> list){
		SaleDayTotal saleDayTotal=new SaleDayTotal();
		if(list.size()>0){
			Object [] objects=list.get(0);
			if(objects!=null&&objects.length>0){
				saleDayTotal.setNum(Integer.parseInt(objects[0].toString()));
				saleDayTotal.setRname(objects[1].toString());
				
			}
			double arrays[]=new double[31];
			double profits=0;
			double sumMoney=0;
			for(Object[] obs:list){
				Integer day=Integer.parseInt(obs[4].toString());
				arrays[day-1]=Double.parseDouble(obs[2].toString());
				sumMoney+=Double.parseDouble(obs[2].toString());
				profits+=Double.parseDouble(obs[3].toString());
			}
			//总金额
			saleDayTotal.setSumMoney(sumMoney);
			//利润
			saleDayTotal.setProfits(profits);
			saleDayTotal.setDays(arrays);
			return saleDayTotal;
		}
		
		return null;
	}
	
	//销售日统计
	@Override
	public List<Object[]> saleDayTotal(VSalelist model,VUser user) {
		// TODO Auto-generated method stub
		
		//1、如果没有选择就返回所有的数据
		
		
		//获取登录的经销商
		
		//2、
		//如果是有选择指定的仓库
		//查询指定仓库的销售额
		
		//如果日期没有选择 就默认当前月
		if(model.getBeginDate()==null){
			model.setBeginDate(new Date());
		}
		
		DateFormat format=new SimpleDateFormat("yyyy-MM");
		String beginDate=format.format(model.getBeginDate());
//		Date date= model.getBeginDate();
//		date.setMonth(date.getMonth()+1);
		Date end=null;
		try {
			 end=format.parse(format.format(model.getBeginDate()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		end.setMonth(end.getMonth()+1);
		String endDate=format.format(end);
//		
//		String hql="select r.ID id,r.NAME rname,sum(t.sale_price*t.number) as 'sum',sum((g.sale_price-g.buy_price)*t.number) as profits,date_format(s.DATE,'%d') as 'day'"
//				+"from xsgl_salelist s join qxgl_user u join rkgl_repertory r join spgl_goods g join xsgl_salelist_item t"
//				+" where " 
//				+" s.USER_ID=u.ID" 
//				+" and r.USER_ID=u.ID" 
//				+" and s.REPERTORY_ID=r.ID"  
//				+" and t.salelist_id=s.ID" 
//				+" and g.id=t.goods_id"
//				+" and u.ID="+user.getId() 
//				+" and r.ID="+model.getRid() 
//				+" and s.DATE>='"+beginDate+"' and s.DATE<='"+endDate+"'"
//				+" group by date_format(s.DATE,'%d')";
//		
		String hql="SELECT" 
					+" r.ID id,"
			        +" r.NAME rname,"
			        +" Round(sum(sli.sale_price*sli.number),2) as 'sum',"
			        +" Round(sum((g.sale_price-g.buy_price)*sli.number),2) as profits,"
			        +" date_format(sl.DATE,"
			        +"'%d') as 'day'"
					+" FROM  `xsgl_salelist` sl"
					+" JOIN `xsgl_salelist_item` sli" 
					+" JOIN `qxgl_user` u"
					+" JOIN `rkgl_repertory` r" 
					+" JOIN `spgl_goods` g"
					+" WHERE sli.`SALELIST_ID`=sl.`ID`" 
					+" AND g.`ID`=sli.`GOODS_ID`" 
					+" AND r.`ID`=sl.`REPERTORY_ID`" 
					+" AND sl.`USER_ID`=u.`ID`"
					+" AND u.`USER_ID`="+user.getId() 
					+" and r.ID="+model.getRid()
					+" and sl.DATE>='"+beginDate+"'" 
			        +" and sl.DATE<='"+endDate+"'" 
			        +" group by date_format(sl.DATE,'%d')";
		
		return salelistDao.findBySql(hql);
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#getuserSaleTotalChart(java.util.List)
	 */
	@Override
	public JFreeChart getSaleTotalChart(List<Object[]> vsls, VSalelist model) {
		// TODO Auto-generated method stub
		JFreeChart chart = null;
		DefaultPieDataset  dataset = new DefaultPieDataset ();
		String chartTitle = "销售统计图";

		try {
			if(model.getOrder().trim().equals("total")){//按照消费金额排序
				chartTitle = "销售金额统计图";
				for(Object[] objarr:vsls){
					dataset.setValue((String)objarr[0],Double.parseDouble(String.valueOf(objarr[1])));
				}
			}else if(model.getOrder().trim().equals("buyPrice")){//按照成本排序
				chartTitle = "销售成本统计图";
				for(Object[] objarr:vsls){
					dataset.setValue((String)objarr[0],Double.parseDouble(String.valueOf(objarr[2])));
				}
			}else if(model.getOrder().trim().equals("profit")){//按照利润排序
				chartTitle = "销售利润统计图";
				for(Object[] objarr:vsls){
					dataset.setValue((String)objarr[0],Double.parseDouble(String.valueOf(objarr[3])));
				}
			}else{
				for(Object[] objarr:vsls){
					dataset.setValue((String)objarr[0],Double.parseDouble(String.valueOf(objarr[1])));
				}
			}
	
			chart = ChartFactory.createPieChart3D(chartTitle,
			  dataset,
			  false,
			  false,
			  false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return chart;
	}
	
	

	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#saleRank(java.lang.Long, com.jxc.model.vo.VSalelist)
	 */
	@Override
	public List<Object[]> saleRank(VSalelist model) {
		// TODO Auto-generated method stub
		List<Object[]> vsls = new ArrayList<Object[]>();
		String sql = " ROUND(SUM(sli.total),2) total,ROUND(SUM(g.buy_price*sli.number),2) buyprice ,ROUND(SUM(sli.total)-SUM(g.buy_price*sli.number),2) profit " +
				"FROM  `xsgl_salelist_item` sli JOIN `spgl_goods` g  JOIN `spgl_brand` b JOIN `spgl_goods_type` gt " +
				"WHERE sli.goods_id=g.id AND g.brand_id=b.id AND  g.goods_type_id=gt.id AND b.user_id='"+model.getUpid();
		
		try{
			if(model.getGroupby().trim().equals("brand")){//通过品牌统计
				sql = " SELECT  b.name bname," + sql + "' GROUP BY b.id ORDER BY total DESC";
			}else if(model.getGroupby().trim().equals("color")){//通过颜色统计
				sql = " SELECT  g.color gcolor," + sql + "' GROUP BY g.color ORDER BY total DESC";
			}else if(model.getGroupby().trim().equals("size")){//通过尺码统计
				sql = " SELECT  g.size gsize," + sql + "' GROUP BY g.size ORDER BY total DESC";
			}else if(model.getGroupby().trim().equals("type")){//通过款号统计
				sql = " SELECT  g.type gtype," + sql + "' GROUP BY g.type ORDER BY total DESC";
			}else if(model.getGroupby().trim().equals("gtype")){//通过商品类型统计
				sql = " SELECT  gt.name gtname," + sql + "' GROUP BY gt.name ORDER BY total DESC";
			}else{//通过品牌统计
				sql = " SELECT  b.name btname," + sql + "' GROUP BY b.id ORDER BY total DESC";
			}
			
			sql += " limit 6";
			vsls = salelistDao.findBySql(sql);
			
		}catch(Exception e){
			e.printStackTrace();
		}		
		
		return vsls;			
		
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.SalelistServiceI#getSaleRankChart(java.util.List, com.jxc.model.vo.VSalelist)
	 */
	@Override
	public JFreeChart getSaleRankChart(List<Object[]> vsls, VSalelist model) {
		// TODO Auto-generated method stub
		JFreeChart chart = null;
		try {
			String chartTitle = "商品销售排行";
			String domainLabel ="品牌";
			if(model.getGroupby().trim().equals("brand")){//通过品牌统计
				chartTitle += "(按品牌)";
			}else if(model.getGroupby().trim().equals("color")){//通过颜色统计
				chartTitle += "(按颜色)";
			}else if(model.getGroupby().trim().equals("size")){//通过尺码统计
				chartTitle += "(按尺码)";
			}else if(model.getGroupby().trim().equals("type")){//通过款号统计
				chartTitle += "(按款号)";
			}else if(model.getGroupby().trim().equals("gtype")){//通过商品类型统计
				chartTitle += "(按商品类型)";
			}else{//通过品牌统计
				chartTitle += "(按品牌)";
			}
			
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();

			//  各曲线名称
			String series1 = "销售额";
			String series2 = "成本";
			String series3 = "利润";
			  
			for(Object[] objarr:vsls){
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[1])),"销售额", (String)objarr[0]);
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[2])),"成本", (String)objarr[0]);
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[3])),"利润", (String)objarr[0]);
			}
			chart = ChartFactory.createBarChart3D(chartTitle, // chart title
					domainLabel, // domain axis label
				    "金额", // range axis label
				    dataset, // data
				    PlotOrientation.VERTICAL, // orientation
				    true, // include legend
				    true, // tooltips
				    false // urls
				    );

		} catch (Exception e) {
			e.printStackTrace();
		}
		return chart;	
		
	}


	
	/*@Override
	public JFreeChart getSaleRankChart(List<Object[]> vsls, VSalelist model) {
		// TODO Auto-generated method stub
		JFreeChart chart = null;
		try {
			String chartTitle = "商品销售排行";
			String domainLabel ="品牌";
			if(model.getGroupby().trim().equals("brand")){//通过品牌统计
				chartTitle += "(按品牌)";
			}else if(model.getGroupby().trim().equals("color")){//通过颜色统计
				chartTitle += "(按颜色)";
			}else if(model.getGroupby().trim().equals("size")){//通过尺码统计
				chartTitle += "(按尺码)";
			}else if(model.getGroupby().trim().equals("type")){//通过款号统计
				chartTitle += "(按款号)";
			}else if(model.getGroupby().trim().equals("gtype")){//通过商品类型统计
				chartTitle += "(按商品类型)";
			}else{//通过品牌统计
				chartTitle += "(按品牌)";
			}
			
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();

			//  各曲线名称
			String series1 = "销售额";
			String series2 = "成本";
			String series3 = "利润";
			  
			for(Object[] objarr:vsls){
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[1])), series1, (String)objarr[0]);
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[2])), series2, (String)objarr[0]);
				dataset.addValue(Double.parseDouble(String.valueOf(objarr[3])), series3, (String)objarr[0]);
			}
			chart = ChartFactory.createLineChart3D(chartTitle, // chart title
					domainLabel, // domain axis label
				    "金额", // range axis label
				    dataset, // data
				    PlotOrientation.VERTICAL, // orientation
				    true, // include legend
				    true, // tooltips
				    false // urls
				    );
//			chart.setBackgroundPaint(Color.white);  
	          
			  
	        // 设置标题的颜色  
	        TextTitle text = new TextTitle(chartTitle);  
	        text.setPaint(new Color(102, 102, 102));  
	        chart.setTitle(text);  
	        XYPlot xyplot = (XYPlot)chart.getXYPlot();  
	        xyplot.setBackgroundPaint(new Color(255, 253, 246));  
	        xyplot.setOutlineStroke(new BasicStroke(3.5f)); // 边框粗细  
	        ValueAxis vaxis = xyplot.getDomainAxis();  
	        vaxis.setAxisLineStroke(new BasicStroke(3.5f)); // 坐标轴粗细  
	        vaxis.setAxisLinePaint(new Color(215, 215, 215)); // 坐标轴颜色  
	        xyplot.setOutlineStroke(new BasicStroke(1.5f)); // 边框粗细  
	        vaxis.setLabelPaint(new Color(10, 10, 10)); // 坐标轴标题颜色  
	        vaxis.setTickLabelPaint(new Color(102, 102, 102)); // 坐标轴标尺值颜色  
	        vaxis.setLowerMargin(0.06d);// 分类轴下（左）边距  
	        vaxis.setUpperMargin(0.14d);// 分类轴下（右）边距,防止最后边的一个数据靠近了坐标轴。
		} catch (Exception e) {
			e.printStackTrace();
		}
		return chart;	
		
	}*/
	
}
